<template>
  <div id="EquipmentBookingApplyPage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">设备筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">设备名称</span>
          <el-input
            class="item-input"
            v-model="queryObj.keyword"
            placeholder="请输入设备名称"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-item">
          <span class="item-label">设备类型</span>
          <el-select
            class="item-input"
            v-model="queryObj.typeId"
            placeholder="请选择设备类型"
            clearable
            @change="searchHandle"
          >
            <el-option label="所有" :value="''" />
            <el-option
              v-for="item in equipmentTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">设备状态</span>
          <el-select
            class="item-input"
            v-model="queryObj.status"
            placeholder="请选择设备状态"
            clearable
            @change="searchHandle"
          >
            <el-option label="所有" :value="''" />
            <el-option label="空闲中" :value="'IDLE'" />
            <!-- <el-option label="预约中" :value="'RESERVEING'" /> -->
            <el-option label="使用中" :value="'IN_USE'" />
            <!-- <el-option label="维护中" :value="'REPAIRING'" /> -->
            <el-option label="损坏" :value="'DAMAGED'" />
            <el-option label="报废" :value="'SCRAPPED'" />
          </el-select>
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">设备列表</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="name" label="设备名称">
            <template #default="scope">
              <div class="equipment-name-wrapper">
                <img
                  :src="
                    (scope.row.photoList && scope.row.photoList[0]?.url) ||
                    require('@/assets/images/defaultDevice.png')
                  "
                  alt="设备图片"
                  class="equipment-photo"
                />
                <div class="equipment-info-wrapper">
                  <span class="equipment-name">
                    {{ scope.row.name }}
                  </span>

                  <span class="equipment-sn"> SN：{{ scope.row.code }} </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="设备类型">
            <template #default="scope">
              <div>{{ scope.row.typeInfo?.name || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="model" label="设备型号" />
          <el-table-column label="设备负责人">
            <template #default="scope">
              <div>{{ scope.row.chargeUserInfo?.name || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="设备状态">
            <template #default="scope">
              <div class="signal-status" :class="scope.row.status">
                {{ statusMap[scope.row.status] }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="申请状态">
            <template #default="scope">
              <div
                class="application-status"
                :class="scope.row.deviceApplicationStatus"
              >
                {{
                  scope.row.deviceApplicationStatus === "NOT_APPLIED"
                    ? "未申请"
                    : "已申请"
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="150">
            <template #default="scope">
              <div
                class="table-btn"
                :class="{
                  disabled:
                    ['REPAIRING', 'DAMAGED', 'SCRAPPED'].includes(
                      scope.row.status
                    ) || scope.row.deviceApplicationStatus !== 'NOT_APPLIED',
                }"
                @click="
                  (!['REPAIRING', 'DAMAGED', 'SCRAPPED'].includes(
                    scope.row.status
                  ) ||
                    scope.row.scope.deviceApplicationStatus ===
                      'NOT_APPLIED') &&
                    applyHandle(scope.row)
                "
              >
                申请
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.page"
        :total="pagination.totalElements"
        :page-size="pagination.size"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 申请设备弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="applyDialogVisible"
      title="申请设备"
      width="50%"
    >
      <div class="handle-message">
        您正在申请设备：{{ currentApplyRow?.name }}
      </div>
      <el-form
        v-if="false"
        ref="applyFormRef"
        :model="applyForm"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="申请原因" prop="reason">
          <el-input v-model="applyForm.reason" placeholder="请输入申请原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitApplyForm"
            :loading="applyFormLoading"
            >申请</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { ListResponseType, PaginationType } from "@/api/globalType";
import { getEquipmentListAPI, typesAPI } from "@/api/service/equipmentManage";
import { EquipmentType, EquipmentStatus } from "@/api/types/equipment";
import {
  createDeviceApplicationAPI,
  CreateDeviceApplicationRequest,
} from "@/api/service/deviceApplicant";

const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");

const statusMap = ref<Record<string, string>>({
  IDLE: "空闲中",
  // RESERVEING: "预约中",
  IN_USE: "使用中",
  // REPAIRING: "维护中",
  DAMAGED: "损坏",
  SCRAPPED: "报废",
});

// 查询条件
const queryObj = ref({
  keyword: "",
  typeId: "",
  status: "",
  belong: "",
});

// 分页
const pagination = ref<PaginationType>({
  page: 1,
  size: 50,
  totalElements: 0,
  totalPages: 0,
});

// 表格数据
const tableData = ref<EquipmentType[]>([]);

// API调用保护状态
const listApiLoading = ref(false);

function getEquipmentList() {
  // 防止并发调用
  if (listApiLoading.value) return;

  listApiLoading.value = true;

  getEquipmentListAPI({
    currentUserCode: userInfo.userCode,
    keyword: queryObj.value.keyword,
    typeId: queryObj.value.typeId,
    status: queryObj.value.status as EquipmentStatus,
    belong: queryObj.value.belong,
    page: pagination.value.page,
    size: pagination.value.size,
  })
    .then((_data: any) => {
      const data = _data as ListResponseType<EquipmentType>;
      tableData.value = data.content;
      pagination.value.page = data.page;
      pagination.value.size = data.size;
      pagination.value.totalElements = data.totalElements;
      pagination.value.totalPages = data.totalPages;
    })
    .catch(() => {
      ElMessage.error("获取设备列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getEquipmentList();

// 筛选
function searchHandle() {
  pagination.value.page = 1;
  getEquipmentList();
}

// 分页大小变化
function sizeChangeHandle(size: number) {
  pagination.value.size = size;
  pagination.value.page = 1;
  getEquipmentList();
}
// 分页当前页变化
function currentChangeHandle(currentPage: number) {
  pagination.value.page = currentPage;
  getEquipmentList();
}

// 获取设备类型列表
const equipmentTypeList = ref<EquipmentType[]>([]);
const equipmentTypeListLoading = ref(false);
function getEquipmentTypeList() {
  if (equipmentTypeListLoading.value) return;
  equipmentTypeListLoading.value = true;
  typesAPI()
    .then((res: any) => {
      equipmentTypeList.value = res.deviceTypes || [];
    })
    .catch(() => {
      ElMessage.error("获取设备类型列表失败");
    })
    .finally(() => {
      equipmentTypeListLoading.value = false;
    });
}
getEquipmentTypeList();

// 申请设备
const applyDialogVisible = ref(false);
const applyFormLoading = ref(false);
const currentApplyRow = ref<EquipmentType>();
const applyFormRef = ref();
const applyForm = ref<CreateDeviceApplicationRequest>({
  deviceId: "",
  reason: "",
  applicantCode: "",
});
// const applyFormRules = {
//   reason: [{ required: true, message: "请输入申请原因", trigger: "blur" }],
// };
function applyHandle(row: EquipmentType) {
  applyDialogVisible.value = true;
  currentApplyRow.value = row;
  applyForm.value.deviceId = row.id || "";
  applyForm.value.applicantCode = userInfo.userCode || "";
}
function submitApplyForm() {
  if (applyFormLoading.value) return;

  applyFormLoading.value = true;
  createDeviceApplicationAPI({
    deviceId: applyForm.value.deviceId,
    reason: applyForm.value.reason,
    applicantCode: applyForm.value.applicantCode,
  })
    .then(() => {
      ElMessage.success("申请设备成功");
      applyDialogVisible.value = false;
      resetApplyForm();
    })
    .catch((error) => {
      ElMessage.error(error.message);
    })
    .finally(() => {
      applyFormLoading.value = false;
    });
}
function resetApplyForm() {
  applyForm.value = {
    deviceId: "",
    reason: "",
    applicantCode: "",
  };
  applyDialogVisible.value = false;
}
</script>

<style scoped lang="scss">
#EquipmentBookingApplyPage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  flex-shrink: 0;
  padding: 1.5rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    padding-top: 1rem;
    padding-left: 1rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    margin-right: 2rem;
    .item-label {
      width: 8rem;
      padding-left: 1rem;
      text-align: left;
      color: $text-color-regular;
    }
    .item-label:first-child {
      padding-left: 0;
    }
    .item-input {
      width: 20rem;
    }
  }
  .search-btn {
    height: 3rem;
    display: flex;
    align-items: center;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
  .add-btn-wrapper {
    position: absolute;
    right: 1rem;
    top: 1rem;
    display: flex;
    align-items: center;
    .add-btn {
      margin-right: 1rem;
    }
    .batch-import-btn {
      margin-right: 1rem;
    }
  }
  .add-btn,
  .batch-import-btn,
  .download-template-btn {
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    margin-top: 1rem;
    padding-left: 1rem;
    flex: 1;
    min-height: 0;
  }
  .application-status.NOT_APPLIED {
    color: $color_brand;
  }
  .application-status.APPROVING {
    color: $color_success;
  }
  .application-status.APPROVED {
    color: $color_success;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .table-btn.disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  .signal-status.IDLE {
    color: #999;
  }
  .signal-status.RESERVEING {
    color: $color_warning;
  }
  .signal-status.IN_USE {
    color: $color_success;
  }
  .signal-status.REPAIRING {
    color: $color_danger;
  }
  .signal-status.DAMAGED {
    color: $color_danger;
  }
  .signal-status.SCRAPPED {
    color: $color_danger;
  }
  .equipment-name-wrapper {
    display: flex;
    align-items: center;
    .equipment-photo {
      width: 5rem;
      height: 5rem;
      border-radius: 0.5rem;
      margin-right: 1rem;
    }
    .equipment-info-wrapper {
      display: flex;
      flex-direction: column;
      .equipment-name {
        padding-top: 0.5rem;
        font-size: $font-size-base;
      }
      .equipment-sn {
        font-size: $font-size-tips;
        color: $text-color-secondary;
      }
    }
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}
:deep(.el-input__inner) {
  text-align: left !important;
}

// 申请设备
.handle-message {
  margin-bottom: 2rem;
  padding-left: 3rem;
  font-size: $font-size-page-menu;
  color: $color_brand;
}
</style>
